package cn.e_eap.esite.manager.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import cn.e_eap.esite.bean.Module;
import cn.e_eap.esite.manager.BaseManager;
import cn.e_eap.esite.manager.ModuleManager;
import cn.e_eap.esite.util.ApplicationException;
import cn.e_eap.esite.web.form.ModuleForm;
import cn.e_eap.esite.web.form.PagerForm;

@Component("moduleManager")
public class ModuleManagerImpl extends BaseManager<Module> implements
		ModuleManager {

	@Override
	public void add(Module module, int parentId) {
		if(module==null) {
                throw new NullPointerException();
        }
		if (module.getSn() == null || module.getSn().length() == 0) {
                throw new ApplicationException("module's serial number could not be null ");
            }
		if(parentId==0) {
			super.add(module);
			return ;
		}
		Module parent = getHibernateTemplate().get(Module.class, parentId);
		module.setParent(parent);
		super.add(module);
	}

	@Override
	public void delete(String ids) {
		super.removeByIds(Module.class, ids);
	}

	//
	// @Override
	// public void update(Module module) {
	// getHibernateTemplate().update(module);
	// }

	@Override
	public List<Module> find(ModuleForm condition, PagerForm pf) {
		if (condition == null) {
			return super.getPageModel(Module.class, pf);
		}
		StringBuilder hql = new StringBuilder();

		if (condition.getSn() != null && condition.getSn().length() > 0) {
			hql.append(" and @.sn like '%").append(condition.getSn()).append("%'");
		}
		if (condition.getName() != null && condition.getName().length() > 0) {
			hql.append(" and @.name like '%").append(condition.getName()).append("%'");
		}
		
		if (condition.getUrl() != null && condition.getUrl().length() > 0) {
			hql.append(" and @.url like '%").append(condition.getUrl()).append("%'");
		}
		if(condition.getParentId()==0){
			hql.append(" and (@.parent=null or @.parent.id=").append(condition.getParentId()).append(")");
		} else {
			hql.append(" and @.parent.id=").append(condition.getParentId());
		}
		hql.append(
				" order by @.level");

		return super.getPageModel(Module.class, hql.toString(), pf);
	}

	@Override
	public Module findById(int id) {
		return getHibernateTemplate().get(Module.class, id);
	}

	@Override
	public Module findByUrl(String url) {
		return super.findUnique(Module.class, " where @.url='"+url+"'");
	}

	@Override
	public Module findBySn(String sn) {
		return super.findUnique(Module.class, " where @.sn='"+sn+"'");
	}

}
